<?php

namespace app\admin\controller;

use app\admin\model\system\SystemUploadfile;
use app\common\controller\AdminController;
use app\common\service\MenuService;
use app\common\service\UploadService;
use think\db\Query;
use think\facade\Cache;
use think\facade\Cookie;


class Ajax extends AdminController
{

    /**
     * 初始化后台菜单地址
     */
    public function initAdmin()
    {
        // 生产模式，获取缓存数据
        if (!config('cache.develop_mode')) {
            $key       = 'initAdmin_' . session('admin.id');
            $cacheData = Cache::get($key);
            if (empty($cacheData)) {
                $cacheData = self::getMenuData();
                Cache::tag('initAdmin')->set($key, $cacheData);
            }
        }
        else {
            // 开发模式，直接获取最新数据
            $cacheData = self::getMenuData();
        }
        return json($cacheData);
    }

    /**
     * 获取菜单数据
     */
    public function getMenuData()
    {
        $menuService = new MenuService(session('admin.id'));
        return [
            'logoInfo' => [
                'title' => sysconfig('site', 'logo_title'),
                'image' => sysconfig('site', 'logo_image'),
                'href'  => __url('index/index'),
            ],
            'homeInfo' => $menuService->getHomeInfo(),
            'menuInfo' => $menuService->getMenuTree(),
        ];
    }

    /**
     * 清除缓存接口
     */
    public function clearCache()
    {
        Cache::clear();
        $this->success('清除缓存成功');
    }

    /**
     * 清除接口文档缓存接口
     */
    public function clearApiCache()
    {
        Cache::tag('api')->clear();
        $this->success('清除接口缓存成功');
    }

    /**
     * 清除用户登录user-token缓存接口
     */
    public function clearUserCache()
    {
        Cache::tag('user')->clear();
        $this->success('清除用户缓存成功');
    }

    /**
     * 获取语言切换列表
     * {"zh-cn":"简体中文","en-us":"English"}
     */
    public function getLanguageList()
    {
        // 允许的语言列表,'zh-cn', 'en-us'
        $allow_lang_list = config('lang.allow_lang_list');
        // 允许的语言列表名称,'简体中文', 'English'
        $allow_lang_name = config('lang.allow_lang_name');
        // 合并数组
        $lang_list['lang_list'] = array_combine($allow_lang_list, $allow_lang_name);
        // 获取cookie当前设置的语言数据
        $lang = Cookie::get(config('lang.cookie_var'));
        if ($lang) {
            $lang_list['lang'] = $lang;
        }
        $this->success('获取语言列表成功', $lang_list);
    }

    /**
     * 语言切换
     */
    public function switchLanguage()
    {
        $lang = $this->request->post('lang');
        Cookie::forever(config('lang.cookie_var'), $lang);
        $this->success('语言切换成功');
    }

    /**
     * 上传文件
     */
    public function upload()
    {
        $this->checkPostRequest();
        $data = [
            'upload_type' => $this->request->post('upload_type'),
            'file'        => $this->request->file('file'),
        ];

        try {

            $upload_service = new UploadService($data['upload_type']);

            $upload_service->validateException($data['file']);

            $result = $upload_service->save($data['file']);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('上传成功', $result);
    }

    /**
     * 上传图片至编辑器
     */
    public function uploadEditor()
    {
        $this->checkPostRequest();
        $data = [
            'upload_type' => $this->request->post('upload_type'),
            'file'        => $this->request->file('upload'),
        ];

        try {
            $upload_service = new UploadService($data['upload_type']);

            $upload_service->validateException($data['file']);

            $result = $upload_service->save($data['file']);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        return json([
            'error'    => [
                'message' => '上传成功',
                'number'  => 201,
            ],
            'fileName' => '',
            'uploaded' => 1,
            'url'      => $result['url'],
        ]);
    }

    /**
     * 获取上传文件列表
     */
    public function getUploadFiles()
    {
        $get         = $this->request->get();
        $page        = isset($get['page']) && !empty($get['page']) ? $get['page'] : 1;
        $limit       = isset($get['limit']) && !empty($get['limit']) ? $get['limit'] : 10;
        $title       = isset($get['title']) && !empty($get['title']) ? $get['title'] : null;
        $mimeType    = isset($get['mime_type']) && !empty($get['mime_type']) ? $get['mime_type'] : null;
        if ($mimeType == '*') {
            $mimeType = null;
        } else if (str_ends_with($mimeType, '*')) { // 如：'image/*'
            $mimeType = str_replace('*', '%', $mimeType);
        } else if (str_contains($mimeType, ',')) {  // 如：'image/png,image/jpeg'
            $mimeType = explode(',', $mimeType);
        }
        $this->model = new SystemUploadfile();
        $count       = $this->model
            ->where(function (Query $query) use ($title, $mimeType) {
                !empty($title) && $query->where('original_name', 'like', "%{$title}%");
                if (is_array($mimeType)) {
                    $query->where('mime_type', 'in', $mimeType);
                } else if (is_string($mimeType)) {
                    $query->where('mime_type', 'like', $mimeType);
                }
            })
            ->count();
        $list        = $this->model
            ->where(function (Query $query) use ($title, $mimeType) {
                !empty($title) && $query->where('original_name', 'like', "%{$title}%");
                if (is_array($mimeType)) {
                    $query->where('mime_type', 'in', $mimeType);
                } else if (is_string($mimeType)) {
                    $query->where('mime_type', 'like', $mimeType);
                }
            })
            ->page($page, $limit)
            ->order($this->sort)
            ->select();
        $data        = [
            'code'  => 0,
            'msg'   => '',
            'count' => $count,
            'data'  => $list,
        ];
        return json($data);
    }

    /**
     * @notes: 根据文件地址获取文件库中的id
     * @author: Jerry
     * @time: 2024/1/5 15:36
     */
    public function getUploadfileIds()
    {
        $this->checkPostRequest();
        // url: 'url1,url2'
        $url = $this->request->post('url');
        $id_list = SystemUploadfile::where('find_in_set(url,"'.$url.'")')->column('id');
        if ($id_list) {
            $ids = join(',', $id_list);
        } else {
            $ids = '';
        }
        $this->success('获取成功', ['ids' => $ids]);
    }
}
